<template>
  <component
    :is="drawerMode ? 'el-drawer' : 'el-dialog'"
    :title="'工单详情'"
    :visible.sync="visibleProxy"
    width="80%"
    :before-close="handleClose"
    class="order-detail-dialog"
    :with-header="true"
    :append-to-body="true"
    :custom-class="drawerMode ? 'order-detail-drawer' : ''"
  >
    <div v-loading="loading" class="order-detail-container">
      <div v-if="orderDetail" class="order-detail">
        <el-tabs type="border-card">
          <el-tab-pane label="基本信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="工单号">{{ orderDetail.工单号 }}</el-descriptions-item>
              <el-descriptions-item label="案号">{{ orderDetail.案号 }}</el-descriptions-item>
              <el-descriptions-item label="案件类型">{{ orderDetail.案件类型 }}</el-descriptions-item>
              <el-descriptions-item label="案由">{{ orderDetail.案由 }}</el-descriptions-item>
              <el-descriptions-item label="标的金额">{{ orderDetail.标的金额 }}</el-descriptions-item>
              <el-descriptions-item label="调解状态">{{ orderDetail.tj_status_text }}</el-descriptions-item>
              <el-descriptions-item label="工单状态">{{ orderDetail.gd_status_text }}</el-descriptions-item>
              <el-descriptions-item label="优先级">{{ orderDetail.yxj_text }}</el-descriptions-item>
              <el-descriptions-item label="调解员">{{ orderDetail.调解员 }}</el-descriptions-item>
              <el-descriptions-item label="调解员分配时间">{{ orderDetail.调解员分配时间 }}</el-descriptions-item>
              <el-descriptions-item label="工单标题" :span="2">{{ orderDetail.工单标题 }}</el-descriptions-item>
              <el-descriptions-item label="诉讼请求" :span="2">{{ orderDetail.诉讼请求 }}</el-descriptions-item>
              <el-descriptions-item label="调解方案" :span="2">{{ orderDetail.调解方案 }}</el-descriptions-item>
              <el-descriptions-item label="争议焦点" :span="2">{{ orderDetail.争议焦点 }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="当事人信息">
            <el-table :data="orderDetail.dsr_arr" style="width: 100%">
              <el-table-column prop="姓名" label="姓名" width="180"></el-table-column>
              <el-table-column prop="证件号码" label="证件号码" width="180"></el-table-column>
              <el-table-column prop="手机号" label="手机号" width="180"></el-table-column>
              <el-table-column prop="dsr_fldw_text" label="法律地位"></el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="争议焦点">
            <el-tag v-for="(item, index) in orderDetail.zyjd_arr" :key="index" style="margin-right: 10px; margin-bottom: 10px;">
              {{ item }}
            </el-tag>
          </el-tab-pane>

          <el-tab-pane label="材料文件">
            <el-tree
              :data="orderDetail.file_tree"
              :props="defaultProps"
              @node-click="handleNodeClick"
              node-key="id"
              default-expand-all
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span v-if="data.type !== 'folder'">
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="previewFile(data)"
                  >
                    预览
                  </el-button>
                </span>
              </span>
            </el-tree>
          </el-tab-pane>

          <!-- 调解结果标签页 -->
          <el-tab-pane label="调解结果">
            <el-form ref="tjForm" :model="tjForm" label-width="120px">
              <el-form-item label="调解意见">
                <el-input
                  type="textarea"
                  v-model="tjForm.调解意见"
                  :rows="4"
                  placeholder="请输入调解意见"
                ></el-input>
              </el-form-item>
              <el-form-item label="调解结果">
                <el-select v-model="tjForm.调解结果" placeholder="请选择调解结果">
                  <el-option label="完成" value="10"></el-option>
                  <el-option label="调解失败" value="20"></el-option>
                  <el-option label="二次调节" value="30"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="转立案备注">
                <el-input
                  type="textarea"
                  v-model="tjForm.转立案备注"
                  :rows="3"
                  placeholder="请输入转立案备注"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitTjResult">提交调解结果</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else-if="!loading" class="no-data">
        未找到工单数据
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog
      title="文件预览"
      :visible.sync="previewDialogVisible"
      append-to-body
      width="60%"
    >
      <div v-if="currentFile" class="file-preview">
        <div v-if="currentFile.type === 'image'" class="image-preview">
          <img :src="currentFile.url" alt="文件预览" />
        </div>
        <div v-if="currentFile.content" class="content-preview">
          <pre>{{ currentFile.content }}</pre>
        </div>
      </div>
    </el-dialog>
  </component>
</template>

<script>
import axios from 'axios';

export default {
  name: 'OrderDetail',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: String,
      required: true,
      default: ''
    },
    drawer: {
      // 父级如果是el-drawer传true，否则不传
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      orderDetail: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      previewDialogVisible: false,
      currentFile: null,
      dialogVisible: false,
      tjForm: {
        调解意见: '',
        调解结果: '',
        转立案备注: ''
      }
    };
  },
  computed: {
    drawerMode() {
      return this.drawer;
    },
    visibleProxy: {
      get() {
        // 优先用父级visible，否则用内部dialogVisible
        return typeof this.visible === 'boolean' ? this.visible : this.dialogVisible;
      },
      set(val) {
        if (typeof this.visible === 'boolean') {
          this.$emit('update:visible', val);
        } else {
          this.dialogVisible = val;
        }
      }
    },
    isMeetingEnded() {
      if (!this.orderDetail) return false;
      // 根据工单状态判断是否已结束
      return this.orderDetail.tj_status === '10' || this.orderDetail.tj_status === 10;
    }
  },
  watch: {
    visible(val) {
      if (val && this.orderId) {
        this.fetchOrderDetail();
      }
    },
    orderId(val) {
      if (this.visibleProxy && val) {
        this.fetchOrderDetail();
      }
    }
  },
  methods: {
    handleClose() {
      this.visibleProxy = false;
    },
    async fetchOrderDetail() {
      this.loading = true;
      try {
        const token = localStorage.getItem('token');
        const id = localStorage.getItem('orderId') || this.orderId;
        
        if (!token || !id) {
          this.$message.error('缺少认证信息或工单ID');
          this.loading = false;
          return;
        }

        const response = await axios.get('http://10.77.162.117:18092/admin/mediation_order/detail', {
          params: { id },
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        if (response.data && response.data.code === 200 && response.data.data && response.data.data.length > 0) {
          this.orderDetail = response.data.data[0];
          // 新增：判断调解状态是否为已结束
          // this.isMeetingEnded = this.orderDetail.tj_status === '10'; // This line is now handled by computed property
        } else {
          this.$message.warning('未找到工单数据');
          this.orderDetail = null;
        }
      } catch (error) {
        console.error('获取工单详情失败:', error);
        this.$message.error('获取工单详情失败');
      } finally {
        this.loading = false;
      }
    },
    handleNodeClick(data) {
      if (data.type !== 'folder') {
        this.previewFile(data);
      }
    },
    previewFile(file) {
      this.currentFile = file;
      this.previewDialogVisible = true;
    },
    // 新增：提交调解结果
    async submitTjResult() {
      try {
        const token = localStorage.getItem('token');
        const id = localStorage.getItem('orderId') || this.orderId;

        if (!token || !id) {
          this.$message.error('缺少认证信息或工单ID');
          return;
        }

        const response = await axios.post('http://10.77.162.117:18092/admin/mediation_order/submit_tj_result', {
          id: id,
          tj_yj: this.tjForm.调解意见,
          tj_jg: this.tjForm.调解结果,
          zla_bz: this.tjForm.转立案备注
        }, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        if (response.data && response.data.code === 200) {
          this.$message.success('调解结果提交成功！');
          this.fetchOrderDetail(); // 刷新工单详情
          this.tjForm = {
            调解意见: '',
            调解结果: '',
            转立案备注: ''
          };
        } else {
          this.$message.error('调解结果提交失败：' + (response.data ? response.data.msg : '未知错误'));
        }
      } catch (error) {
        console.error('提交调解结果失败:', error);
        this.$message.error('提交调解结果失败');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.order-detail-container {
  max-height: 70vh;
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.file-preview {
  max-height: 60vh;
  overflow-y: auto;

  .image-preview {
    text-align: center;
    
    img {
      max-width: 100%;
      max-height: 60vh;
    }
  }

  .content-preview {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    
    pre {
      white-space: pre-wrap;
      word-wrap: break-word;
      font-family: 'Courier New', Courier, monospace;
      line-height: 1.5;
    }
  }
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 16px;
}
</style> 